'use client';

import { useState, useEffect } from 'react';
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { uploadFile } from '@/apis/admin/file';

interface ImageUploadProps {
  value?: {
    id: string;
    url: string;
  };
  onChange?: (value: { id: string; url: string }) => void;
}

const ImageUpload: React.FC<ImageUploadProps> = ({ value, onChange }) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  console.log(imageUrl);
  
  useEffect(() => {
    if (value?.url) {
      setImageUrl(value.url);
    }
  }, [value]);

  const handleChange = async (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      try {
        const { fileId, url } = await uploadFile(info.file.originFileObj);
        setImageUrl(url);
        onChange?.({ id: fileId, url });
      } catch (error) {
        message.error('Upload failed');
      } finally {
        setLoading(false);
      }
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <Upload
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      customRequest={({ file, onSuccess }) => {
        setTimeout(() => {
          onSuccess?.('ok');
        }, 0);
      }}
      beforeUpload={(file) => {
        // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        // if (!isJpgOrPng) {
        //   message.error('You can only upload JPG/PNG file!');
        // }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('Image must smaller than 2MB!');
        }
        return isLt2M;
      }}
      onChange={handleChange}
    >
      {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' ,height:'100%',objectFit:'contain'}} /> : uploadButton}
    </Upload>
  );
};

export default ImageUpload;